/*
MIT License

Copyright (c) 2007 Ralf Kornmann

All right reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/

#include "stdafx.h"
#include "Host.h"
#include "FunctionHook.h"
#include "Plugin.h"

CFunction::CFunction (LPCSTR strProc)
	: m_strName (strProc)
	, m_Proc (NULL)
{
}

const std::string& CFunction::GetName () const
{
	return m_strName;
}

void CFunction::AddHook (CFunctionHook* pFunction)
{
	m_Functions.push_back (pFunction);
}

void CFunction::RemoveHook (CFunctionHook* pFunction)
{
	TFunctionHookVector::iterator iter = std::find (m_Functions.begin(), m_Functions.end(), pFunction);

	if (iter != m_Functions.end())
		m_Functions.erase (iter);
}

void CFunction::UpdateState (HMODULE hModule)
{
	FARPROC newProc = NULL;

	if (hModule != NULL)
		newProc = GetProcAddress (hModule, m_strName.c_str());

	if (m_Proc == newProc)
		return;

	m_Proc = newProc;

	for (TFunctionHookVector::iterator iter = m_Functions.begin() , end = m_Functions.end() ; iter != end ; ++iter)
		(*iter)->UpdateState (hModule, m_Proc);
}

///////////////////////////////////////////////////////////////////////////////////////////////////

CModule::CModule (LPCWSTR strModule)
	: m_strName (strModule)
	, m_hModule (NULL)
{
	UpdateState ();
}

CModule::~CModule ()
{
	for (TFunctionVector::iterator iter = m_Functions.begin() , end = m_Functions.end() ; iter != end ; ++iter)
		delete (*iter);

	for (TFunctionVector::iterator iter = m_Functions.end() , begin = m_Functions.begin() ; iter != begin ; --iter)
		delete (*iter);
}

const std::wstring& CModule::GetName () const
{
	return m_strName;
}

CFunction* CModule::GetFunction (LPCSTR strProc)
{
	for (TFunctionVector::iterator iter = m_Functions.begin() , end = m_Functions.end(); iter != end; ++iter)
		if ((*iter)->GetName() == strProc)
			return (*iter);

	CFunction* pNewFunction = new CFunction (strProc);

	m_Functions.push_back (pNewFunction);

	pNewFunction->UpdateState (m_hModule);

	return pNewFunction;
}

void CModule::UpdateState ()
{
	HMODULE newModule = GetModuleHandleW (m_strName.c_str());

	if (m_hModule == newModule)
		return;

	m_hModule = newModule;

	for (TFunctionVector::iterator iter = m_Functions.begin() , end = m_Functions.end(); iter != end; ++iter)
		(*iter)->UpdateState (m_hModule);
}

///////////////////////////////////////////////////////////////////////////////////////////////////

extern CMasterHost* TheMasterHost;

CHost::CHost ()
	: m_RefCount (0)
	, m_CodeMemorySize (0)
	, m_MemoryBlockSize (0)
	, m_pCodeMemory (NULL)
{
	InitFunctions ();

	SYSTEM_INFO SysInfo;

	GetSystemInfo (&SysInfo);
	m_MemoryBlockSize = SysInfo.dwPageSize;
}

CHost::~CHost ()
{
	for (TModuleVector::iterator iter = m_Modules.begin() , end = m_Modules.end() ; iter != end ; ++iter)
		delete (*iter);

	TheMasterHost->RemoveHost (this);
}

HRESULT STDMETHODCALLTYPE CHost::QueryInterface(REFIID riid, void **ppvObject)
{
	if (ppvObject == NULL)
		return E_POINTER;

	if (memcmp (&riid, &__uuidof(IUnknown), sizeof(GUID)) == 0)
		*ppvObject = (IUnknown*)this;
	else if (memcmp (&riid, &__uuidof(IUAHHost), sizeof(GUID)) == 0)
		*ppvObject = (IUAHHost*)this;
	else *ppvObject = NULL;

	if (*ppvObject == NULL)
		return E_NOINTERFACE;
	
	AddRef ();
	return S_OK;
}

ULONG STDMETHODCALLTYPE CHost::AddRef( void)
{
	return InterlockedIncrement (&m_RefCount);
}

ULONG STDMETHODCALLTYPE CHost::Release( void)
{
	LONG result = InterlockedDecrement (&m_RefCount);

	if (result == 0)
		delete this;

	return result;
}

HRESULT STDMETHODCALLTYPE CHost::CreateFunctionHook(LPCWSTR lpModuleName, LPCSTR lpProcName, FARPROC newFunction, DWORD Flags, IUAHHockedFunction** ppFunction)
{
	if (ppFunction == NULL)
		return E_POINTER;

	CFunctionHook* pHook = new CFunctionHook (*this, lpModuleName, lpProcName, Flags, newFunction);
	pHook->AddRef ();

	*ppFunction = pHook;

	if ((Flags & UAH_HOOK_FLAG_MONITOR) == UAH_HOOK_FLAG_MONITOR)
	{
		CModule* pMod = GetModule (lpModuleName);
		
		CFunction* pFunc = pMod->GetFunction (lpProcName);

		pFunc->AddHook (pHook);
	}

	return S_OK;
}

HRESULT STDMETHODCALLTYPE CHost::LoadPlugin (LPCWSTR lpPlugin, LPCWSTR lpConfig)
{
	XML::IXMLDOMDocumentPtr doc;

    if (doc.CreateInstance (__uuidof(XML::DOMDocument)) != S_OK)
		return E_FAIL;

    if (doc->loadXML (lpConfig) != VARIANT_TRUE)
		return E_FAIL;

    XML::IXMLDOMElementPtr root = doc->documentElement;

	if (!(BOOL)root)
		return E_FAIL;

	return LoadPlugin (lpPlugin, (XML::IXMLDOMElement*)root);
}

typedef IUAHPlugin* (WINAPI *CreatePluginFunc) (XML::IXMLDOMElement* configElement);

HRESULT STDMETHODCALLTYPE CHost::LoadPlugin (LPCWSTR lpPlugin, XML::IXMLDOMElement* configElement)
{
	if (configElement == NULL)
		return E_FAIL;

	HMODULE hModule = LoadLibraryW (lpPlugin);

	if (hModule == NULL)
		return E_FAIL;

	CreatePluginFunc CreatePlugin = (CreatePluginFunc)GetProcAddress (hModule, "CreatePlugin");

	if (CreatePlugin == NULL)
		return E_FAIL;

	IUAHPlugin* pPlugin = CreatePlugin (configElement);

	if (pPlugin == NULL)
		return E_FAIL;

	m_Plugins.push_back (new CPlugin (hModule, pPlugin));

	return S_OK;
}

HRESULT STDMETHODCALLTYPE CHost::LoadPlugins (XML::IXMLDOMElement* configElement)
{
	HRESULT hr = S_OK;

	XML::IXMLDOMElementPtr config = configElement;

	XML::IXMLDOMNodeListPtr pluginElements = config->GetchildNodes ();

	for (int Index = 0 ; Index < pluginElements->length ; Index++)
	{
		XML::IXMLDOMElementPtr plugin = pluginElements->item[Index];

		if (plugin->tagName != _bstr_t(L"Plugin"))
			continue;

		_variant_t value = plugin->getAttribute ("Name");

		if (value.vt != VT_BSTR)
			continue;

		_bstr_t name (value);
		XML::IXMLDOMElementPtr pluginConfig = plugin->GetfirstChild();

		if (LoadPlugin (name, pluginConfig) != S_OK)
			hr = S_FALSE;
	}

	return hr;
}

HRESULT STDMETHODCALLTYPE CHost::LoadPlugins (LPCWSTR lpConfig)
{
	XML::IXMLDOMDocumentPtr XmlDoc;
	HRESULT hr = XmlDoc.CreateInstance (__uuidof(XML::DOMDocument));

	if (hr != S_OK)
		return hr;

	if (XmlDoc->loadXML (lpConfig) != VARIANT_TRUE)
		return E_FAIL;

	return LoadPlugins (XmlDoc->documentElement);
}

HRESULT STDMETHODCALLTYPE CHost::LoadPluginsFromFile (LPCWSTR lpFile)
{
	XML::IXMLDOMDocumentPtr XmlDoc;
	HRESULT hr = XmlDoc.CreateInstance (__uuidof(XML::DOMDocument));

	if (hr != S_OK)
		return hr;

	if (XmlDoc->load (lpFile) != VARIANT_TRUE)
		return E_FAIL;

	return LoadPlugins (XmlDoc->documentElement);
}

BOOL CHost::GetThreadContext (HANDLE hThread, LPCONTEXT lpContext)
{
	return m_GetThreadContext (hThread, lpContext);
}

BOOL CHost::SetThreadContext (HANDLE hThread, const CONTEXT* lpContext)
{
	return m_SetThreadContext (hThread, lpContext);
}

BOOL CHost::VirtualProtect (LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect)
{
	return m_VirtualProtect (lpAddress, dwSize, flNewProtect, lpflOldProtect);
}

BOOL CHost::WriteProcessMemory (HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten)
{
	return m_WriteProcessMemory (hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten);
}

FARPROC CHost::GetPatchFunctionBlock ()
{
	if (m_CodeMemorySize < 64)
	{
		m_pCodeMemory = (BYTE*)VirtualAlloc (NULL, m_MemoryBlockSize, MEM_COMMIT, PAGE_EXECUTE);
		m_CodeMemorySize = m_MemoryBlockSize;
	}

	BYTE* pResult = m_pCodeMemory;
	m_CodeMemorySize -= 64;
	m_pCodeMemory = &m_pCodeMemory[64];

	return (FARPROC)pResult;
}

void CHost::RemoveMonitor (CFunctionHook* pFunction)
{
	CModule* pMod = GetModule (pFunction->GetModuleName ().c_str());

	if (pMod == NULL)
		return;
	
	CFunction* pFunc = pMod->GetFunction (pFunction->GetProcName().c_str());

	if (pFunc == NULL)
		return;

	pFunc->RemoveHook (pFunction);
}

void CHost::InitFunctions ()
{
	HMODULE hKernel = GetModuleHandle (L"Kernel32");

	m_GetThreadContext = (GetThreadContextFunc)GetProcAddress (hKernel, "GetThreadContext");
	m_SetThreadContext = (SetThreadContextFunc)GetProcAddress (hKernel, "SetThreadContext");
	m_VirtualProtect = (VirtualProtectFunc)GetProcAddress (hKernel, "VirtualProtect");
	m_WriteProcessMemory = (WriteProcessMemoryFunc)GetProcAddress (hKernel, "WriteProcessMemory");
}

CModule* CHost::GetModule (LPCWSTR lpModuleName)
{
	for (TModuleVector::iterator iter = m_Modules.begin() , end = m_Modules.end(); iter != end; ++iter)
		if ((*iter)->GetName() == lpModuleName)
			return (*iter);

	CModule* pNewModule = new CModule (lpModuleName);

	m_Modules.push_back (pNewModule);

	return pNewModule;
}

void CHost::UpdateState ()
{
	for (TModuleVector::iterator iter = m_Modules.begin() , end = m_Modules.end(); iter != end; ++iter)
		(*iter)->UpdateState ();
}

///////////////////////////////////////////////////////////////////////////////////////////////////

CMasterHost::CMasterHost ()
{
}

CMasterHost::~CMasterHost ()
{
}

void CMasterHost::UpdateHostState ()
{
	for (THostVector::iterator iter = m_Hosts.begin() , end = m_Hosts.end(); iter != end; ++iter)
		(*iter)->UpdateState ();

	UpdateState ();
}

void CMasterHost::AddHost (CHost* pHost)
{
	m_Hosts.push_back (pHost);
}

void CMasterHost::RemoveHost (CHost* pHost)
{
	THostVector::iterator iter = std::find (m_Hosts.begin(), m_Hosts.end(), pHost);

	if (iter != m_Hosts.end())
		m_Hosts.erase (iter);
}